import { Injectable } from '@nestjs/common';
import { CreateWaybillDto } from './dto/index';
import { ListWaybillDto } from './dto';
import { UserDto } from '../user/user.decorator';
import { InjectRepository } from '@nestjs/typeorm';
import { WaybillEntity } from './entities/waybill.entity';
import { Repository } from 'typeorm';
import { WaybillStatusEnum } from 'src/common/enum';

@Injectable()
export class WaybillService {
  constructor(
    @InjectRepository(WaybillEntity)
    private readonly waybillRep: Repository<WaybillEntity>,
  ) {}
  async findAll(query: ListWaybillDto, user: UserDto) {
    const entity = this.waybillRep.createQueryBuilder('waybill');
    const pageSize = query.pageSize || 10;
    const pageNum = query.pageNum || 1;
    const enterpriseId = user.enterpriseId;

    if (enterpriseId) {
      entity.andWhere(`waybill.enterpriseId = :enterpriseId`, { enterpriseId });
    }

    if (query.waybillStatus) {
      entity.andWhere('waybill.waybillStatus IN (:...waybillStatus)', { waybillStatus: query.waybillStatus });
    }

    entity.skip(pageSize * (pageNum - 1)).take(pageSize);

    let [list, total] = await entity.getManyAndCount();
    const totalPage = Math.ceil(total / pageSize);

    list = list.map((item) => ({
      ...item,
      waybillStatus: WaybillStatusEnum[item.waybillStatus],
    }));

    return {
      list,
      total,
      totalPage,
      pageNum,
      pageSize,
    };
  }

  create() {}
}
